//环境判断
var urlTest = window.location.href.toString().indexOf('52tt.com'); //是否52tt.com, 内部环境不上报
var urlHttpsTest = window.location.href.toString().indexOf('https://'); //https判断

//初始化
function logs_init() {};
var myLogs = new logs_init();
myLogs.cacheKey = 'tt_log_cache_1';
myLogs.reportUri = urlHttpsTest == -1 ? 'http://statis.52tt.com/statis/webstatis' : 'https://statis.52tt.com/statis/webstatis';
myLogs.reportKey = {
    main: '6600',
    error: '66000001',
    performance: '66000002',
    visit: '66000003',
};
myLogs.uuidCacheKey = 'tt_uuid';
myLogs.maxCache = 1024 * 30;

//实时上报处理
myLogs.directReport = function () {}

var _ps = _ps || []; //性能日志
var _es = _es || []; //错误日志
var _vs = _vs || []; //访问日志
var _vst = 0; //访问时间
var _vsp = 'home'; //首页

Date.prototype.Format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}



//性能统计
function _pr(txt, time) {
    _ps.push({'params': {'name': txt, 'holdTime': time}, 'bizId':myLogs.reportKey.performance });
};


//错误统计
function _er(msg, uri, line) {
    var uri = uri || '';
    var line = line || '';
    var temp = true;
    _.each(_es, function (e) {
        if (e.params.name == msg && e.params.line == line) {
            temp = false;
        }
    })
    //console.log(temp);
    if (temp) {
        _es.push({'params': {'name': msg, 'uri': uri, 'line': line}, 'bizId':myLogs.reportKey.error });
        myLogs.directReport();
    }
}

//html5 错误发生时
window.onerror = function (m, u, l) {
    _er(m, u, l);
};

//上报格式化
myLogs.dataFormat = function (data) {
    return [data];
}

//获取或生成uuid
myLogs.getUuid = function () {
    var localStore = localStorage.getItem(myLogs.uuidCacheKey);
    if (localStore) {
        return localStore;
    } else {
        var temp = _.random(0, 100000) + 'uuid' + _.now();
        localStorage.setItem(myLogs.uuidCacheKey, temp);
        return temp;
    }
}

//延时调用请求
var _delayBounceContainer;
var _delayBounce = function (idle, action) {
    return function () {
        var ctx = this, args = arguments
        clearTimeout(_delayBounceContainer)
        _delayBounceContainer = setTimeout(function () {
            action.apply(ctx, args)
        }, idle)
    }
}

//重置日志数据
myLogs.resetLog = function () {
    //数据结构置空
    _ps = []; //性能日志置空
    _es = []; //错误日志置空
    _vs = []; //访问日志置空
}


//排重并加入标记
myLogs.uniqueLog = function (data) {
    var temp = _.uniq(data);
    var dn = (new Date()).Format("yyyy-MM-dd hh:mm:ss"); //当前时间
    temp = _.each(temp, function (e) {
        //e.bizId = myLogs.reportKey;
        e.client_timestamp = dn;
    })
    return temp;
}

//项目地址
myLogs.currentUrl = _getProjectUrl();
//console.log(myLogs.currentUrl);

//日志数据结构
myLogs.data = {
    header: {
        title: '项目名称',
        url: '',
        ver: 1.0,
        recordId: '',
        uid: '',
        appId: 0,//app id,
        //deviceId:'设备id', //通过js-api获取
        platform: 'android',
        deviceOsVer: '4.4',
        devicepixelRatio: 1,//设备像素比
    },
    body: {
        performance: [],
        error: [],
        visit: [],
        events: []
    }
}
var timing = performance.timing;
//访问统计
function _vr(txt) {
    var holdTime;
    if(_vst == 0){
        holdTime =  (_.now() - timing.loadEventEnd).toString();
    }else {
        holdTime = (_.now() - _vst).toString();
    }
    _vs.push({'params': {type: 'visit', 'name': _vsp, 'holdTime': holdTime}, 'bizId':myLogs.reportKey.visit});
    _vst = _.now(); //设置为最后一次访问时间
    _vsp = txt; //页面内容

    myLogs.directReport();//直接触发上报
};

myLogs.loadLog = function() {

    function performanceInit(){

        //html5 performance接口
        var timing = performance.timing;
        myLogs.performanceData = {
            readyStart: timing.fetchStart - timing.navigationStart, //准备新页面时间耗时
            redirectTime: timing.redirectEnd - timing.redirectStart, //redirect 重定向耗时
            appcacheTime: timing.domainLookupStart - timing.fetchStart, //Appcache 耗时
            unloadEventTime: timing.unloadEventEnd - timing.unloadEventStart, //unload前文档耗时
            lookupDomainTime: timing.domainLookupEnd - timing.domainLookupStart, //DNS查询耗时
            connectTime: timing.connectEnd - timing.connectStart, //TCP连接耗时
            requestTime: timing.responseEnd - timing.requestStart, //request请求耗时
            initDomTreeTime: timing.domInteractive - timing.responseEnd, //请求完毕至DOM加载
            domReadyTime: timing.domComplete - timing.domInteractive, //生成dom树耗时,过早获取可能为0
            loadEventTime: timing.loadEventEnd - timing.loadEventStart, //load事件耗时
            loadTime: timing.loadEventEnd - timing.navigationStart, //从开始至load总耗时,过早获取时,loadEventEnd有时会是0
        };

        if(timing.loadEventEnd == 0){
            setTimeout(function(){
                performanceInit();
            }, 500);
        }
        else {
            _pr('准备新页面', myLogs.performanceData.readyStart.toString());
            _pr('DNS查询', myLogs.performanceData.lookupDomainTime.toString());
            _pr('TCP连接', myLogs.performanceData.connectTime.toString());
            _pr('请求耗时', myLogs.performanceData.requestTime.toString());
            _pr('DOM加载', myLogs.performanceData.initDomTreeTime.toString());
            _pr('渲染DOM树', myLogs.performanceData.domReadyTime.toString());
            _pr('资源载入', myLogs.performanceData.loadEventTime.toString());
            _pr('准备完毕', myLogs.performanceData.loadTime.toString());


            //发送缓存数据,并清空缓存
            myLogs.initLocalCache = function (key) {
                var localStore = localStorage.getItem(key);
                if (localStore) {
                    //如果cache有未发送的数据则发送,成功后清除cache
                    myApp.requestPostApi(myLogs.reportUri, JSON.parse(localStore), function () {
                        localStorage.removeItem(key);
                    }, function () {
                        //发送失败,超过指定大小清空cache
                        if (localStore.length > myLogs.maxCache) {
                            localStorage.removeItem(key);
                        }
                    }, true);
                }
            }

            //收集头部信息并排重body
            myLogs.initLog = function () {

                myLogs.data.header.recordId = _.now() + myLogs.getUuid();
                myLogs.data.header.title = document.title;
                myLogs.data.header.url = myLogs.currentUrl;
                myLogs.data.header.uid = _getUrlParam('uid') || ''; //uid
                myLogs.data.header.uuid = myLogs.getUuid(); //uuid
                myLogs.data.header.appId = _getUrlParam('app') || ''; //app id
                myLogs.data.header.ver = document.getElementById('html-version').content ? document.getElementById('html-version').content : '1.0'; //读取版本信息
                myLogs.data.header.platform = myApp.device.os; //操作系统平台
                myLogs.data.header.deviceOsVer = myApp.device.osVersion; //操作系统版本
                myLogs.data.header.devicepixelRatio = myApp.device.pixelRatio.toString(); //retina像素比率

                //日志拼接
                myLogs.data.body.performance = myLogs.uniqueLog(_ps); //性能日志
                myLogs.data.body.error = myLogs.uniqueLog(_es); //错误
                myLogs.data.body.visit = myLogs.uniqueLog(_vs); //错误
            }

            //var reports = _.debounce(myLogs.mergeReport(), 2000);

            //日志上报
            myLogs.mergeReport = function () {

                //延迟报告
                function DelayReport() {
                    myLogs.initLog();
                    //console.log(JSON.stringify(myLogs.data));
                    //myApp.alert(JSON.stringify(myLogs.data));
                    myLogs.resetLog(); //重置数据
                    myApp.requestPostApi(myLogs.reportUri, myLogs.dataFormat(myLogs.data), function(){
                        myLogs.succeedReport();
                    }, function(){
                        myLogs.failReport();
                    }, true);
                }

                //延时执行,有点击则重置时间
                _delayBounce(1500, function () {
                    DelayReport();
                })();

                //console.log(_.isArray(myLogs.data));
                //console.log(JSON.stringify(myLogs.dataFormat(myLogs.data)));

            }

            //上报成功
            myLogs.succeedReport = function () {
                //myLogs.resetLog(); //重置数据
            }

            //上报失败
            myLogs.failReport = function () {
                var localStore = localStorage.getItem(myLogs.cacheKey);
                //延迟100ms落地到本地存储
                setTimeout(function () {
                    if (localStore) {
                        var temp = JSON.parse(localStore);
                        if (!_.isArray(temp)) {
                            temp = myLogs.dataFormat(temp);
                            console.log(JSON.stringify(temp));
                        }
                        temp.push(myLogs.data);
                        localStorage.setItem(myLogs.cacheKey, JSON.stringify(temp));

                    } else {
                        localStorage.setItem(myLogs.cacheKey, JSON.stringify(myLogs.dataFormat(myLogs.data)));
                    }
                    myLogs.resetLog(); //重置数据
                }, 100);
            }

            //发送缓存数据,并清空缓存
            myLogs.initLocalCache(myLogs.cacheKey);

            //收集信息,完成日志合并上报
            myLogs.mergeReport();

            //统计实时上报处理
            myLogs.directReport = function () {
                myLogs.mergeReport();
            };
        }
    }

    if(performance){
        performanceInit();
    }
};


//线上环境执行统计
if(urlTest != -1){
    window.onload = myLogs.loadLog();
}

